# -*- coding:utf-8 -*-

import os, sys
import logging
# from tornado import log
from tornado.options import options
from utils import strutils
from configure import config


def initLogger(logfile_name=None):
    """ 初始化日志输出
    @param     log_path        日志输出路径
    @param     logfile_name    日志文件名
    """
    print 'init logger ...'
    options.logging = 'debug'
    logger = logging.getLogger()
    if logfile_name:
        log_dir = os.path.join(options.root_dir, config.LOG_PATH)
        strutils.makeDirs(log_dir)
        logfile = os.path.join(log_dir, logfile_name)
        handler = logging.handlers.TimedRotatingFileHandler(logfile, 'D')
        fmt_str = '[%(levelname)1.1s %(asctime)s] %(message)s'
    else:
        handler = logging.StreamHandler()
        fmt_str = '[%(levelname)1.1s %(asctime)s] %(message)s'
#         fmt_str = '%(color)s[%(levelname)1.1s %(asctime)s]%(end_color)s %(message)s'
#     fmt = log.LogFormatter(fmt=fmt_str, datefmt=None)
    fmt = logging.Formatter(fmt_str)
    handler.setFormatter(fmt)
    logger.addHandler(handler)


def info(*argl, **argd):
    func_name, argd = _logFuncName(*argl, **argd)
    logging.info(_log(func_name, *argl, **argd))


def warn(*argl, **argd):
    func_name, argd = _logFuncName(*argl, **argd)
    logging.warn(_log(func_name, *argl, **argd))
    

def debug(*argl, **argd):
    func_name, argd = _logFuncName(*argl, **argd)
    logging.debug(_log(func_name, *argl, **argd))


def error(*argl, **argd):
    logging.error('*' * 40)
    func_name, argd = _logFuncName(*argl, **argd)
    logging.error(_log(func_name, *argl, **argd))
    logging.error('*' * 40)


exception = error


def _log(func_name, *argl, **argd):
    _log_msg = func_name
    for l in argl:
        if type(l) == tuple :
            ps = str(l)
        else:
            try:
                ps = "%r" % l
            except:
                ps = str(l)
        if type(l) == str: 
            _log_msg += ps[1:-1] + ' '
        elif type(l) == unicode:
            _log_msg += ps[2:-1] + ' '
        else:
            _log_msg += ps + ' '
    if len(argd) > 0:
        _log_msg += str(argd)
    return _log_msg


def _logFuncName(*argl, **argd):
    """ 获取方法名
    * logger.xxx(... caller=self) for instance method
    * logger.xxx(... caller=cls) for @classmethod
    """
    caller_cls_name = ""
    try :
        _caller = argd.get("caller", None)
        if _caller :
            if not hasattr(_caller, "__name__"):
                _caller = _caller.__class__
            caller_cls_name = _caller.__name__
            del argd["caller"]
    except :
        pass

    func_name_str = "[" + caller_cls_name + "." + sys._getframe().f_back.f_back.f_code.co_name + "] "
    return func_name_str, argd

